package com.songcan.oauth.handle;

import cn.hutool.core.util.ObjectUtil;
import com.songcan.common.vo.UserDetailsNew;
import com.songcan.model.oauth.SysMenu;
import com.songcan.oauth.lister.AbstractAuthenticationSuccessEventHandler;
import com.songcan.oauth.service.SysMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Component
@Slf4j
public class AuthenticationSuccessEventHandler extends AbstractAuthenticationSuccessEventHandler {

    private SysMenuService sysMenuService;
    private RedisTemplate redisTemplate;

    @Autowired
    public AuthenticationSuccessEventHandler(SysMenuService sysMenuService,RedisTemplate redisTemplate){
        this.sysMenuService = sysMenuService;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void handle(Authentication authentication) {
        log.info("用户：{} 登录成功", authentication.getPrincipal());

        UserDetailsNew userDetailsNew = UserDetailsNew.class.cast(authentication.getPrincipal());
        Collection<GrantedAuthority> jsonObjects = userDetailsNew.getAuthorities();
        List<String> roleIds = jsonObjects.parallelStream().filter(Objects::nonNull).map(String::valueOf).collect(Collectors.toList());
        List<SysMenu> list = sysMenuService.selectMenuByUserId(roleIds,null,null);
        if(list.size()>0) {
            for (int i = 0; i < list.size(); i++) {
                SysMenu menuVo = list.get(i);
                if(Objects.nonNull(menuVo)){
                    String scope = menuVo.getScope();
                    String key = "AUTH:MENU:" + menuVo.getRole()+":"+menuVo.getMethod();
                    if(ObjectUtil.isNotEmpty(key) && ObjectUtil.isNotEmpty(menuVo.getUrl()) && ObjectUtil.isNotEmpty(scope)){
                        redisTemplate.opsForHash().put(key, menuVo.getUrl(), scope);
                        redisTemplate.expire(key, 3, TimeUnit.HOURS);
                    }
                }
            }
        }
    }
}
